<template>
  <main-content title="售后订单">
    <template #tab-bar>
      <el-radio-group
        v-model="currentFilter"
        @change="handleFilterChange"
      >
        <el-radio-button
          v-for="(item, index) in filterList"
          :key="index"
          plain
          :label="item.value"
        >
          {{ item.label }}（{{
            item.count }}）
        </el-radio-button>
      </el-radio-group>
    </template>
    <template #search-bar>
      <search-bar inline>
        <template #normal>
          <el-form-item label="售后单号">
            <el-input
              v-model="form.id"
              clearable
              placeholder="请输入售后单号"
            />
          </el-form-item>
          <el-form-item label="订单号">
            <el-input
              v-model="form.orderNo"
              clearable
              placeholder="请输入订单号"
            />
          </el-form-item>
          <el-form-item label="客户唯一标识">
            <el-input
              v-model="form.unionId"
              clearable
              placeholder="请输入客户唯一标识"
            />
          </el-form-item>
          <el-form-item label="售后状态">
            <el-select
              v-model="form.status"
              clearable
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <!--          <el-form-item label="联系人号码">-->
          <!--            <el-input-->
          <!--              v-model="form.userPhone"-->
          <!--              placeholder="联系人号码"-->
          <!--            />-->
          <!--          </el-form-item>-->

          <el-form-item label="申请时间">
            <el-date-picker
              v-model="orderTime"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :default-time="defaultTime1"
            />
          </el-form-item>
        </template>
      </search-bar>
    </template>

    <LayoutTable
      ref="tokensManage"
      url="/extensions/merchant/order/exception/getOrderPage"
      :set-search="setSearch"
      disable-auto-height
      :param="{ ...form }"
    >
      <el-table-column
        prop="id"
        label="售后单号"
        width="80"
      />
      <el-table-column
        prop="orderNo"
        label="订单号"
        width="200"
      />
      <el-table-column
        prop="createTime"
        label="申请时间"
        width="180"
      >
        <template #default="scope">
          {{ formatTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column
        label="用户ID"
        width="180"
      >
        <template #default="props">
          {{ props.row?.user?.id }}
        </template>
      </el-table-column>
      <el-table-column
        prop="unionID"
        label="客户唯一标识"
        width="180"
      >
        <template #default="props">
          {{ props.row?.user?.unionId }}
        </template>
      </el-table-column>
      <el-table-column
        prop="payOfCurrencyCount"
        label="退款金额"
        width="180"
      >
        <template #default="props">
          <!-- {{ props.row.payOfCurrencyCount }}积分 + {{ props.row.payOfMoney / 100 }}元 -->
          {{ getPointsAndMoneyString(props.row) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="userPhone"
        label="联系人号码"
        min-width="180"
      />
      <el-table-column
        prop="serviceStr"
        label="类型"
        width="180"
      />
      <el-table-column
        prop="status"
        label="售后状态"
        min-width="180"
      >
        <template #default="scope">
          {{ getOrderStatus(scope.row.status) }}
        </template>
      </el-table-column>
      <el-table-column
        label="商品规格名称"
        width="230"
      >
        <template #default="props">
          {{ (props.row?.order?.goodsName ?? '') + ' - ' + (props.row?.order?.productName ?? '') }}
        </template>
      </el-table-column>
      <!-- <el-table-column
        prop="storeProcessTime"
        label="处理时间"
        min-width="180"
      >
        <template #default="scope">
          {{ formatTime(scope.row.storeProcessTime) }}
        </template>
      </el-table-column> -->
      <el-table-column
        prop="refundTime"
        label="退款时间"
        width="180"
      >
        <template #default="props">
          {{ formatTime(props.row.refundTime) }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        fixed="right"
        width="100"
      >
        <template #default="scope">
          <div>
            <el-button
              v-has="['08040301']"
              link
              type="primary"
              @click="goOrderDetail(scope.row)"
            >
              查看详情
            </el-button>
          </div>
          <div />
        </template>
      </el-table-column>
    </LayoutTable>
    <exportData
      v-model:show-dialog="showExportData"
      :search-data="form"
      title="售后订单-商城"
      export-type="afterSalesOrderExport"
      :time-key="orderTime"
      :time-field="['queryCreateTimeStart', 'queryCreateTimeEnd']"
    />
  </main-content>
</template>
<script lang="ts">
export default {
  name: "AfterSalesServiceOrderList",
};
</script>
<script lang="ts" setup>
import type { Ref } from "vue";
import type { IAfterSaleOrderPageData } from "@/api/modules/pointsMall"
import moment from "moment";
import { getPointsAndMoneyString } from "@/utils"
import { IOrderPageRow } from "@/api/modules/order";
import { getAbnormalStatistics } from "@/api/pointsMall";
import { AfterSalesServiceOrderStatus } from "@/config/dictionary";
import { useMallConfig } from "@/views/pointsMall/compositions/useMallConfig";
import exportData from "@/components/exportData/exportData.vue";
import { UnwrapRef } from "vue";
const router = useRouter();
const { mallConfig } = useMallConfig();

const orderTime = ref("");
const setSearch = ref(0);
const showExportData = ref(false);
const currentFilter = ref(-1);
const filterList:Ref<{label: string; value: string; count: number}[]> = ref(
  JSON.parse(JSON.stringify(AfterSalesServiceOrderStatus))
);

const statusOptions = computed(() => {
  return AfterSalesServiceOrderStatus.filter(item => item.value !== '-1')
})

const form:UnwrapRef<IAfterSaleOrderPageData> = reactive({
  id: "",
  orderNo: "",
  unionId: "",
  status: "",
  userPhone: "",
  queryCreateTimeStart: "",
  queryCreateTimeEnd: "",
  queryInsIds: <number[]>[],
});

// watch(form, () => {
//   getOrderStaticsList()
// })

const defaultTime1 = reactive([
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59),
]);

watch(orderTime, (val) => {
  if (val) {
    form.queryCreateTimeStart = String(new Date(val[0]).getTime());
    form.queryCreateTimeEnd = String(new Date(val[1]).getTime());
  } else {
    form.queryCreateTimeStart = "";
    form.queryCreateTimeEnd = "";
  }
});

const handleFilterChange = (radioValue: '-1' | string) => {
  if (Number(radioValue) == -1) {
    form.status = "";
  } else {
    form.status = radioValue;
  }
};

const formatTime = (value: string) => {
  if (value) {
    return moment(value).format("YYYY.MM.DD HH:mm:ss");
  }
};

const getOrderStatus = (status: string) => {
  return filterList.value.find((item) => item.value === status)?.label ?? "--";
};

const getOrderStaticsList = async () => {
  filterList.value.forEach(i => i.count = 0)
  const rs = await getAbnormalStatistics({ 
    ...form,
    status: "",
    businessType: "mall", 
    businessId: mallConfig.value.id,
  });
  if (rs.code === 200) {
    rs.payload?.forEach((item: { count: number; status: string }) => {
      filterList.value.forEach((el) => {
        if (item.status == el.value) {
          el.count = item.count;
        }
      });
    });
  }
};

const goOrderDetail = (row: IOrderPageRow) => {
  router.push({
    path: `/mall/order/afterSalesList/detail`,
    query: {
      id: row.orderId,
    },
  });
};

const onSearch = () => {
  setSearch.value++;
};
const store = useStore();
// 监听机构
const insId = computed(() => {
  return store.state.insId.insId;
});
watch(
  () => insId,
  () => {
    getOrderStaticsList();
  },
  {
    deep: true,
  }
);
onMounted(() => {
  getOrderStaticsList();
});
</script>
<style lang="scss" scoped></style>
